#include "captchaassisttask.h"
#include "captchaassistdialog.h"
#include "libs/controls/toastlabel.h"
#include "liveinfoview.h"
#include "liverecorder.h"
#include "livestatusview.h"
#include "liveviewmanager.h"
#include "livewindow.h"
#include "presentermonitor.h"
#include "yingce.h"
#include "yingcewindow.h"
#include <QTimer>

CaptchaAssistTask::CaptchaAssistTask(LiveRecorder* recorder, QObject* parent)
    : yc::Task { 0, true, 0, parent }, recorder_(recorder)
{
}

void CaptchaAssistTask::startImpl()
{
    // 停止监测
    recorder_->monitor()->stop();

    auto win = recorder_->liveViewManager()->window();
    dialog_ = new CaptchaAssistDialog(win, YingCeWindow::instance());
    connect(dialog_, &CaptchaAssistDialog::discarded, this, &CaptchaAssistTask::terminate);
    const auto rc = YingCeWindow::instance()->geometry();
    const int x = rc.left() + (rc.width() - 500) / 2;
    const int y = rc.top() + (rc.height() - 680) / 2;
    dialog_->setGeometry(x, y, 500, 680);
    dialog_->setWindowModality(Qt::ApplicationModal);
    dialog_->show();

    captcha_timer_ = new QTimer(this);
    captcha_timer_->setInterval(30000);
    captcha_timer_->setSingleShot(true);
    connect(captcha_timer_, &QTimer::timeout, this, [this] {
        qDebug() << "CaptchaAssist: get captcha timeout";
        if (!captcha_shown_ && ++captcha_retry_ < 5) {
            startRequest();
        } else {
            startNext();
        }
    });

    reload_timer_ = new QTimer(this);
    reload_timer_->setInterval(10000);
    reload_timer_->setSingleShot(true);
    connect(reload_timer_, &QTimer::timeout, this, &CaptchaAssistTask::startRequest);

    step_count_ = recorder_->liveViewManager()->needCaptchaCount();
    success_count_ = 0;
    pos_ = -1;
    startNext();
}

void CaptchaAssistTask::terminateImpl()
{
    if (captcha_timer_) {
        captcha_timer_->stop();
    }
    if (reload_timer_) {
        reload_timer_->stop();
    }
    // 恢复监测
    recorder_->monitor()->start();
}

void CaptchaAssistTask::startRequest()
{
    qDebug() << "CaptchaAssist: pos:" << pos_ << "reload retry:" << reload_retry_
             << "captcha retry:" << captcha_retry_;
    auto win = recorder_->liveViewManager()->window();
    win->setCurrent(pos_);
    auto view = win->views().at(pos_);
    if (auto info_view = qobject_cast<LiveInfoView*>(view)) {
        if (info_view->passedCaptcha()) {
            startNext();
        } else {
            disconnect(info_view, nullptr, this, nullptr);
            connect(info_view, &LiveInfoView::captchaStateChanged, this,
                    &CaptchaAssistTask::onCaptchaStateChanged);
            // 开始验证倒计时
            captcha_timer_->start();
            dialog_->showLoading();
            info_view->getLiveInfo(0, yc::KUAISHOW_PLATFORM_TYPE, getAnchorId(pos_), 15000,
                                   LiveHandler(this, [this](int presenter, const QString& args) {
                                       Q_UNUSED(presenter)
                                       if (isRunning()) {
                                           if (args.isEmpty()
                                               || (!captcha_shown_ && ++reload_retry_ < 5)) {
                                               qDebug() << "CaptchaAssist: retry to get live info.";
                                               captcha_timer_->stop();
                                               reload_timer_->start();
                                           } else {
                                               startNext();
                                           }
                                       }
                                   }));
        }
    } else if (auto status_view = qobject_cast<LiveStatusView*>(view)) {
        if (status_view->passedCaptcha()) {
            startNext();
        } else {
            disconnect(status_view, nullptr, this, nullptr);
            connect(status_view, &LiveStatusView::captchaStateChanged, this,
                    &CaptchaAssistTask::onCaptchaStateChanged);
            // 开始验证倒计时
            captcha_timer_->start();
            dialog_->showLoading();
            status_view->getLiveStatus(
                    0, yc::KUAISHOW_PLATFORM_TYPE, getAnchorId(pos_), 15000,
                    LiveHandler(this, [this](int presenter, const QString& args) {
                        Q_UNUSED(presenter)
                        if (isRunning()) {
                            if (args.isEmpty() || (!captcha_shown_ && ++reload_retry_ < 5)) {
                                captcha_timer_->stop();
                                reload_timer_->start();
                            } else {
                                startNext();
                            }
                        }
                    }));
        }
    }
}

void CaptchaAssistTask::startNext()
{
    captcha_timer_->stop();
    reload_timer_->stop();

    auto win = recorder_->liveViewManager()->window();
    if (++pos_ >= win->views().size()) {
        Q_ASSERT(dialog_);
        dialog_->deleteLater();
        yc::ToastLabel::showMessage(
                tr("Verification has been completed. Please continue to use it."),
                YingCeWindow::instance());
        recorder_->monitor()->start();
        Q_EMIT finished();
    } else {
        captcha_shown_ = false;
        captcha_retry_ = 0;
        reload_retry_ = 0;
        startRequest();
    }
}

void CaptchaAssistTask::onCaptchaStateChanged(bool passed)
{
    if (!passed) {
        captcha_timer_->stop();
        dialog_->hideLoading();
        captcha_shown_ = true;
        yc::ToastLabel::showMessage(tr("Please complete the verification assistance (%1/%2).")
                                            .arg(pos_)
                                            .arg(step_count_),
                                    dialog_, 6000);
    }
}

QString CaptchaAssistTask::getAnchorId(int index)
{
    static QString anchors[10] = { "3x7cff8hm8b9uwi", "pubg98k416",  "lol__tft", "KPL704668133",
                                   "x9988888",        "ksaxinnb",    "w5556666", "Mubai0806",
                                   "qiming188",       "zj2632726957" };
    if (index < 0)
        index = 0;
    else if (index > 9)
        index = 9;
    return anchors[index];
}
